/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.ubb.bibliospring.rsclient;

import edu.ubb.bibliospring.common.dto.AuthorDto;
import java.util.List;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

public class AuthorManager {
    
    private static final String BASE_URL = "http://localhost:8080/biblio-spring-api/rest/author";

    public List<AuthorDto> getAllAuthors() {
        Client client = ClientBuilder.newClient();
        WebTarget target = client.target(BASE_URL);
        return target.request(MediaType.APPLICATION_JSON_TYPE).get(new GenericType<List<AuthorDto>>() {
        });
    }

    public AuthorDto getAuthorById(int id) {
        Client client = ClientBuilder.newClient();
        WebTarget target = client.target(BASE_URL + "/" + id);
        AuthorDto authorResponse = null;
        Response response = target.request(MediaType.APPLICATION_JSON_TYPE).get();
        if (response != null && Status.Family.SUCCESSFUL == response.getStatusInfo().getFamily()) {
            authorResponse = response.readEntity(AuthorDto.class);
            return authorResponse;
        } else {
            System.err.println("There was an error fetching service response");
            System.err.println(response);
            return null;
        }
    }

    public AuthorDto insertAuthor(AuthorDto author) {
        Client client = ClientBuilder.newClient();
        WebTarget target = client.target(BASE_URL);

        return target.request(MediaType.APPLICATION_JSON).post(Entity.entity(author, MediaType.APPLICATION_JSON), AuthorDto.class);
    }

    public AuthorDto updateAuthor(AuthorDto author) {
        Client client = ClientBuilder.newClient();
        WebTarget target = client.target(BASE_URL);

        return target.request(MediaType.APPLICATION_JSON_TYPE).put(Entity.entity(author, MediaType.APPLICATION_JSON), AuthorDto.class);
    }

    public void deleteAuthor(AuthorDto author) {
        Client client = ClientBuilder.newClient();
        WebTarget target = client.target(BASE_URL + "/" + author.getId());

        target.request(MediaType.APPLICATION_JSON_TYPE).delete();
    }
}